import axios from 'axios'
import cookie from 'js-cookie'
import router from '@/router/index'
import { Message } from 'element-ui'

const errorCode = {
  1004: '登录已过期，请重新登录',
  1001: '用户名或密码错误',
}

const service = axios.create({
  baseURL: 'http://localhost:3000',
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  },
  timeout: 9999,
})

service.interceptors.request.use(
  (config) => {
    const token = cookie.get('token')
    console.log(token, 'token')
    if (token) {
      config.headers.token = token
    } else {
      // if (router.app._route.name !== 'login') {
      //   router.push('/login')
      //   return
      // }
    }

    return config
  },
  (err) => {}
)
service.interceptors.response.use(
  (response) => {
    if (response.data.errorCode === '1004') {
      Message({
        message: errorCode[response.data.errorCode],
        type: 'error',
      })
      cookie.remove('token')
      router.push('/login')
      return
    }
    return response.data
  },
  (err) => {}
)

export default service
